<?php

namespace App\Common\Cache;

use EasySwoole\ORM\DbManager;

use App\Common\RedisCache;
use App\Model\Article\ {
    Comments as CommentsModel
};

/**
 * @description: 评论缓存
 */
class CommentCache extends Cache
{
    /**
     * @description: 删除缓存
     * @param {*}
     * @return {*}
     */    
    public function del($args)
    {
        if ($this->cache) {
            switch ($args['func']) {
                case 'afterCreate':
                    $this->afterCreate($args['param']);
                    break;
                case 'afterAudit':
                    $this->afterAudit($args['param']);
                    break;
                case 'beforeDelete':
                    $this->beforeDelete($args['param']);
                    break;
            }
        }
    }

    /**
     * @description: 创建后
     * @param array $param 保存内容
     * @return {*}
     */
    protected function afterCreate($param)
    {
        $key  = 'article:' . $param['article_id'] .  ':comments' . ':page:*';
        $keys = RedisCache::keys($key);
        if ($keys) {
            RedisCache::del($keys);
        }
    }

    /**
     * @description: 审核后
     * @param {*} $param
     * @return {*}
     */
    protected function afterAudit($param)
    {
        $article_ids = DbManager::getInstance()->invoke(function ($client) use ($param) {
            $ids = explode(',', $param['id']);
            $model = CommentsModel::invoke($client);
            return $model->where('id', $ids, 'in')->column('article_id');
        });
        $article_ids = array_unique($article_ids);
        $keys = [];
        foreach ($article_ids as $article_id) {
            $key  = 'article:' . $article_id .  ':comments' . ':page:*';
            $keys = array_merge($keys, RedisCache::keys($key));
        }
        if ($keys) {
            RedisCache::del($keys);
        }
    }

    /**
     * @description: 删除前
     * @param {*} $param
     * @return {*}
     */
    protected function beforeDelete($param)
    {
        $article_ids = DbManager::getInstance()->invoke(function ($client) use ($param) {
            $ids = explode(',', $param['id']);
            $model = CommentsModel::invoke($client);
            return $model->where('id', $ids, 'in')->column('article_id');
        });
        $article_ids = array_unique($article_ids);
        $keys = [];
        foreach ($article_ids as $article_id) {
            $key  = 'article:' . $article_id .  ':comments' . ':page:*';
            $keys = array_merge($keys, RedisCache::keys($key));
        }
        if ($keys) {
            RedisCache::del($keys);
        }
    }
}